package com.company.阻塞队列;

import com.sun.org.apache.bcel.internal.generic.ATHROW;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ProjectName: 复习java
 * @Package: com.company.阻塞队列
 * @ClassName: demo3
 * @Author: wym
 * @Date: 2020/9/29 15:49
 * @Version: 1.0
 */
class ShareData{
    private int number=0;
    private Lock lock=new ReentrantLock();
    //状态 await() 和
    private Condition condition=lock.newCondition();
    //增加方法
    public void  decrement() throws Exception{
        lock.lock();
        try{
            while (number!=0){
                //不能 生成
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+""+number);
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    //减少方法
    public void  reduce() throws Exception{
        lock.lock();
        try{
            while (number==0){
                //不能 生成
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+""+number);
            //唤醒全部
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

/**
 * 线程 操作资源类
 * 判断 干活 通知
 */
public class demo3 {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(()->{
            for (int i = 1; i <=5 ; i++) {

                try {
                    shareData.reduce();
                    System.out.println();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        },"name1").start();

        new Thread(()->{
            for (int i = 1; i <=5; i++) {
                try {
                    shareData.decrement();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },"name2").start();
    }
}
